package com.qf.business;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther: Song
 * @Date: 2022-03-17 19:45
 *	瓦达大大哇
 */
@RestController
public class BusinessController {

    @Autowired
    DiscoveryClient discoveryClient;
    //负载均衡
    AtomicInteger cont = new AtomicInteger(1);

    /**
     *  用户下单接口
     */
    @GetMapping("/hello")
    public void hello() throws IOException {
        //根据服务名查询服务信息
        List<ServiceInstance> list = discoveryClient.getInstances("storage");
        //获取一个实例化对象
        ServiceInstance instance = list.get(cont.getAndAdd(1)%list.size());
        //获取 storage 服务的主机地址
        String host = instance.getHost();
        //获取 storage 服务的端口号
        int port = instance.getPort();
        //组成连接地址
        URL url = new URL("http://" + host + ":" + port + "/deduct");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //建立连接
        connection.connect();
        if (connection.getResponseCode() == 200) {
            //说明请求成功
            //dafawfa打我发发大瓦房
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String s = br.readLine();
            System.out.println("s = " + s);
        }
    }

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/hello2")
    public void hello2() {
        List<ServiceInstance> list = discoveryClient.getInstances("storage");
        ServiceInstance instance = list.get(cont.getAndAdd(1) % list.size());
        String host = instance.getHost();
        int port = instance.getPort();
        String url = "http://storage:" + port + "/deduct";

        String s = restTemplate.getForObject(url, String.class);
        System.out.println("s = " + s);
    }
}
